﻿using System;
using System.Collections.Generic;
using System.Text;
using FlexminAPI;
using ICSharpCode.SharpZipLib.Zip;
using System.Xml;
using System.IO;
using FlexLib.FileTree;

namespace FlexLib.Plugins
{
	public class Package
	{
		private PluginInfo info;

		public PluginInfo Info
		{
			get { return info; }
		}

		private PluginAssemblyPaths assemblyPaths;

		public PluginAssemblyPaths AssemblyPaths
		{
			get { return assemblyPaths; }
		}
/*
		private FileTreeNode userFiles;

		public FileTreeNode UserFiles
		{
			get { return userFiles; }
		}

		private FileTreeNode adminFiles;

		public FileTreeNode AdminFiles
		{
			get { return adminFiles; }
		}
*/
		private const string GENERAL_SETTINGS_FILE = "module.xml";

		public Package(string path)
		{
			ZipFile zipFile = new ZipFile(path);

			ZipEntry entry = zipFile.GetEntry(GENERAL_SETTINGS_FILE);

			StreamReader entryReader = new StreamReader(zipFile.GetInputStream(entry));
			string settings = entryReader.ReadToEnd();
			ParseSettings(settings);

			zipFile.Close();
		}

		private void ParseSettings(string settings)
		{
			XmlDocument xmlDoc = new XmlDocument();
			xmlDoc.LoadXml(settings);

			XmlNode rootNode = null;
			foreach (XmlNode subNode in xmlDoc.ChildNodes)
			{
				if (subNode.Name == "FlexminModule")
				{
					rootNode = subNode;
					break;
				}
			}

			if (rootNode == null)
				throw new ArgumentException("Root node not found");

			foreach (XmlNode groupNode in rootNode.ChildNodes)
			{
				switch (groupNode.Name)
				{
					case "dll":
						assemblyPaths = XmlPluginSerialization.ParseDllPath(groupNode);
						break;
					case "info":
						info = XmlPluginSerialization.ParseInfo(groupNode);
						break;
				}
			}
		}

		public Package()
		{
			
		}
	}
}
